import puppeteer from 'puppeteer';
import { getUrlParams } from '../utils/index.js';
import config from '../utils/constant.js'

// JTNBZ4HK4K3005551
export async function getMainUrl(code) {
  let browser;
  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();
    // 出发反爬虫机制，限制访问
    await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
    await page.goto('https://www.toyodiy.com/parts/q?vin=' + code);
    await Promise.race([
      page.waitForSelector('#page'),
      page.waitForSelector('.err'),
    ])
    const r = await page.$('#wRES > table > tbody > tr:nth-child(2) > td.m > a')
    // 获取res的href值
    if (!r) {
      browser.close();
      return false
    }
    const href = await page.evaluate(r => r.href, r);
    browser.close();
    return getUrlParams(href)
  } catch (error) {
    console.log('getMainUrl: ', error)
    browser && browser.close();
    return false
  }
}

// 获取四大类的洁面数据
export async function getCategoryData(key) {
  if (!key) return false
  let browser;
  try {
    const url = `${config.BASE_URL}/parts/${key}.html`
    browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
    await page.goto(url)
    await page.waitForSelector('.diag-list', {
      timeout: 20000
    })
    const res = await page.$('.diag-list')
    if (!res) {
      browser.close();
      return false
    }
    const r = await page.evaluate(() => {
      const list = document.querySelectorAll('.diag-list > div');
      return [...list].map(item => {
        let h = item?.querySelector('a')?.getAttribute('href');
        if (h) {
          h = getUrlParams(h)
        }
        return {
          // 原生js获取href属性
          key: h,
          text: item?.innerText
        }
      })
    }, res);
    browser.close();
    return r
  } catch (error) {
    console.log('getCategoryData: ', error)
    browser && browser.close();
    return false
  }
}
